package demo.web.tag;

import demo.utils.JdbcPage;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: zigang.wang
 * Date: 12-3-19
 * Time: 上午10:49
 * To change this template use File | Settings | File Templates.
 */
public class PageTag extends TagSupport{
    private int curPage = 1;
    private int totalCount;
    private int pageSize = 10;//显示多少页码
    private int viewCount;//每页显示几条记录
    private JdbcPage page;
    private boolean useDefaultStyle=true;//是否使用默认样式表,如果不用,则用户需要提供CSS

    public JdbcPage getPage() {
        return page;
    }

    public void setPage(JdbcPage page) {
        this.page = page;
    }

    public int getCurPage() {
        return curPage;
    }

    public void setCurPage(int curPage) {
        this.curPage = curPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getViewCount() {
        return viewCount;
    }

    public void setViewCount(int viewCount) {
        this.viewCount = viewCount;
    }

    public boolean isUseDefaultStyle() {
        return useDefaultStyle;
    }

    public void setUseDefaultStyle(boolean useDefaultStyle) {
        this.useDefaultStyle = useDefaultStyle;
    }

    public int doStartTag() throws JspException {
        if(page == null) return SKIP_BODY;
        totalCount = (int)page.getTotalElements();
        viewCount = page.getPageSize();
        curPage = page.getCurPage();
        if(totalCount<=viewCount){
            return SKIP_BODY;
        }
        String bar="";
        if(useDefaultStyle){
            bar+=getDefaultStyle();
        }
        try {
            bar+= "<div style='margin:1px 0px;clear:both'>\n";
            bar += getNavigatorBar();
            //输出结束标记
            bar += "</div>";
            pageContext.getOut().write(bar);
            return SKIP_BODY;
        }
        catch (IOException ioe) {
            throw new JspException(ioe.getMessage());
        }
    }

    private String getDefaultStyle() {
        return "";
    }

    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }

    /**
     * 根据指定类型获得导航条预先设计的导航条

     *
     * @return 返回导航条的HTML代码,若指定类型不存在,返回""
     */
    private String getNavigatorBar() {
        String url = "";
        Map map = pageContext.getRequest().getParameterMap();
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            String value = ((String []) map.get(key))[0];
            try {
                value = URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!key.trim().equalsIgnoreCase("curPage")) {
                if (url.trim().length() == 0) {
                    url = url + key + "=" + value;
                } else {
                    url = url + "&" + key + "=" + value;
                }
            }
        }

        url = "?" + url.trim();

        if (url.endsWith("?")) {
            url = url + "curPage=";
        } else {
            url = url + "&curPage=";
        }
        int totalPage;
        if (totalCount % viewCount == 0) {
            totalPage = totalCount / viewCount;
        } else {
            totalPage = totalCount / viewCount + 1;
        }
        String bar;
        StringBuffer selText = new StringBuffer();
        boolean nextDisabled = false;
        boolean prevDisabled = false;
        if (curPage >= totalPage)
            nextDisabled = true;
        if (curPage <= 1)
            prevDisabled = true;

        int prevOrNextCount;

        if (pageSize % 2 == 0) {
            prevOrNextCount = pageSize / 2;
        } else {
            prevOrNextCount = (pageSize - 1) / 2;
        }

        int firstPage = 1;
        int lastPage = totalPage;
        if (totalPage < curPage + pageSize) {
            lastPage = totalPage;
            firstPage = totalPage-pageSize;
            if(firstPage<1){
                firstPage = 1;
            }
        } else {
            if (curPage - prevOrNextCount > 0) {
                firstPage = curPage - prevOrNextCount;
            }
            if (firstPage + prevOrNextCount * 2 < totalPage) {
                lastPage = firstPage + prevOrNextCount * 2;
            }
        }

        String firstText = ""; //首  页

        String prevText = "";  //上一页

        String nextText = "";  //下一页

        String lastText = "";  //最后一页

        String pagesText="";//中间的页码

        String nav_redirectStyle="border:1px solid #ddd;padding:1px 6px 2px 6px;margin:1px;text-decoration:none;color:#000;font-size:14px;font-weight:bold";
        String nav_num="border:1px solid #ddd;padding:1px 6px 2px 6px;margin:1px;text-decoration:none;color:#000;font-size:14px;font-weight:bold";
        String nav_curPageStyle="border:1px solid #ddd;padding:1px 6px 2px 6px;margin:1px;text-decoration:none;color:darkblue;font-size:14px;font-weight:bold;background-color:#f8f8f8;";
        if (!prevDisabled) {
            firstText = "<span style='"+nav_redirectStyle+"'><a href=\""+url+"1\"><span style='font-size:10px;vertical-align:middle;'>|</span>&lsaquo;</a></span>";
            prevText = "<span style='"+nav_redirectStyle+"'><a href=\""+url+ (curPage - 1) + "\" >&lsaquo;&lsaquo;</a></span>\n";
        }
        if (!nextDisabled) {
            nextText = "<span style='"+nav_redirectStyle+"'><a href=\""+url + (curPage + 1) + "\" >&rsaquo;&rsaquo;</a></span>";
            lastText = "<span style='"+nav_redirectStyle+"'><a href=\""+url + totalPage + "\" >&rsaquo;<span style='font-size:10px;vertical-align:middle;'>|</span></a></span>\n";
        }
        for(int i=firstPage;i<=lastPage;i++){
            if(curPage==i){
                pagesText+="<span style='"+nav_curPageStyle+"'><a >"+i+"</a></span>";
            }else{
                pagesText+="<span style='"+nav_num+"'><a href=\""+url+i+"\" >"+i+"</a></span>\n";
            }
        }
        bar = firstText + " \n " + prevText + " \n " +pagesText+" \n "+ nextText + " \n " + lastText + " \n" + selText.toString() + "\n";

        return bar;
    }
}
